<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\card\Type;
use app\common\model\Machine;
use app\common\model\Merchant;
use app\common\model\Merchantuser;
use app\common\model\Mycard;
use app\common\model\Mycardlog;
use app\common\model\Regionserviceuser;
use Exception;
use fast\Random;
use think\Db;

/**
 * 三方接口
 */
class Trilateral extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    function get_address($address){
        preg_match('/(.*?(省|自治区|北京|天津|上海|重庆))/', $address, $matches);
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = preg_replace('/(.*?(省|自治区|北京|天津|上海|重庆))/','', $address, 1);
        }
        preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
         if (count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address = str_replace($city, '', $address);
        }
        preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
         if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }
         if(!isset($province)) return false;
         return $province."-".$city."-".$area;
    }
    /**
     * 新增店铺
     * */
    public function merchantAdd(){
        $data=[
            ['name', 'require', '店铺名称不能为空'],
            ['address', 'require', '店铺地址不能为空'],
            //['classify', 'require', '店铺地址不能为空'],
            ['lon', 'require', '经纬度不能为空'],
            ['lat', 'require', '经纬度不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if($this->request->param("mobile") && !empty($this->request->param("mobile"))){
            if (!$this->request->param("mobile") || !\think\Validate::regex($this->request->param("mobile"), "^1\d{10}$")) {
                $this->error(('手机号不正确'));
            }
           /* $user=Merchantuser::field("1")->where(["mobile"=>$params["mobile"]])->find();
            if(!empty($user)) $this->error("该手机号码已存在");*/
        }
        $model=new Merchant();
        $merchant=$model->where(["is_trila"=>'1',"fly_id"=>$params["fly_id"]])->find();
        Db::startTrans();
        try {
            $classify=$this->get_address($params["address"]);
            $params["classify"]=$classify?$classify:'';
            $params["account"]="13888888888";
            $user=Merchantuser::field("1")->where(["mobile"=>$params["account"],"is_trila"=>1])->find();
            if(empty($user)){
                $user_data=[
                    "is_super"=>1,
                    "mobile"=> $params["account"],
                    "name"=>"飞狗平台超管账号",
                    //"username"=>"feigou",
                    "password"=>'12345678',
                    "is_trila"=>1,
                ];
                //$params["mobile"]=$params["account"];
                $user_data['salt'] = Random::alnum();
                $user_data['password'] = md5(md5($user_data['password']) . $user_data['salt']);
            }
            unset($params["account"]);
            /*$user_data=[
                "is_super"=>1,
                "mobile"=>$params["account"],
                "name"=>$params["name"]."超管账号",
                //"username"=>$params["account"],
                "password"=>$params["password"],
            ];
            $params["mobile"]=$params["account"];
            $user_data['salt'] = Random::alnum();
            $user_data['password'] = md5(md5($user_data['password']) . $user_data['salt']);
            unset($params["account"]);
            unset($params["password"]);
            if(isset($params["regionserviceuser_id"])){
                $regionservice=Regionserviceuser::field("regionservice_id")->where(["id"=>$params["regionserviceuser_id"]])->find();
                $params["regionservice_id"]=$regionservice["id"];
            }*/
            if(empty($merchant)){
                $params["is_trila"]=1;
                $params["createtime"]=time();
                $params["status"]='1';
                $highest_price=Type::field("price")->find(30);
                $params["fly_price"]=$highest_price["price"];
                $ret=$model->allowField(true)->save($params);
            }else{
                $ret=$merchant->allowField(true)->save($params);
            }
            /*$user_data['merchant_id'] = $ret;
            Merchantuser::create($user_data);*/
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success('新增成功');
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 修改店铺信息
     * */
    public function merchantEdit(){
        $data=[
            ['fly_id', 'require', '店铺id不能为空'],
            ['name', 'require', '店铺名称不能为空'],
            ['address', 'require', '店铺地址不能为空'],
            //['classify', 'require', '店铺地址不能为空'],
            ['lon', 'require', '经纬度不能为空'],
            ['lat', 'require', '经纬度不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if($this->request->param("mobile") && !empty($this->request->param("mobile"))){
            if (!$this->request->param("mobile") || !\think\Validate::regex($this->request->param("mobile"), "^1\d{10}$")) {
                $this->error(('手机号不正确'));
            }
        }
        $merchant=Merchant::where(["fly_id"=>$params["fly_id"],"is_trila"=>1])->find();
        //if(empty($merchant)) $this->error("店铺不存在");
        Db::startTrans();
        try {
            $classify=$this->get_address($params["address"]);
            $params["classify"]=$classify?$classify:'';
            if(empty($merchant)){
                $params["is_trila"]=1;
                $params["createtime"]=time();
                $params["status"]='1';
                $highest_price=Type::field("price")->find(30);
                $params["fly_price"]=$highest_price["price"];
                $model=new Merchant();
                $ret=$model->allowField(true)->save($params);
            }else{
                $ret=$merchant->allowField(true)->save($params);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success('修改成功');
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 删除店铺
     * */
    public function merchantdel(){
        if (!$this->request->param("fly_id")) $this->error("店铺id不能为空");
        $merchant=Merchant::where(["fly_id"=>$this->request->param("fly_id"),"is_trila"=>1])->find();
        if(empty($merchant)) $this->error("店铺不存在");
        Db::startTrans();
        try {
            $merchant->delete();
            Machine::where(["merchant_id"=>$merchant["id"]])->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }
    /**
     * 添加机器
     * */
    public function machineAdd(){
        $data=[
            ['id', 'require', '机器序号不能为空'],
            ['machineID', 'require', '机器编号不能为空'],
            ['fly_id', 'require', '店铺id不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $merchant=Merchant::where(["fly_id"=>$params["fly_id"],"is_trila"=>1])->find();
        if(empty($merchant)) $this->error("店铺不存在");
        $model=new Machine();
        $machine=$model->where(["fly_id"=>$params["fly_id"],"machineID"=>$params["machineID"]])->find();
        Db::startTrans();
        try {
            if(empty($machine)){
                $params["merchant_id"]=$merchant["id"];
                $ret=$model->allowField(true)->save($params);
                $data=$model->getData();
                $code=$model->createWxCode($data["machineID"]);
                if($code["code"]==0) $this->error($code["msg"]);
            }else{
                $ret=$machine->allowField(true)->save($params);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success('添加成功');
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 修改机器
     * */
    public function machineEdit(){
        if (!$this->request->param("id")) $this->error("机器序号不能为空");
        $machine=Machine::where(["id"=>$this->request->param("id")])->find();
        if(empty($machine)){
            $model=new Machine();
            $params = $this->request->param();
            $model->allowField(true)->save($params);
            $data=$model->getData();
            $code=$model->createWxCode($data["machineID"]);
            if($code["code"]==0) $this->error($code["msg"]);
        }else{
            $params = $this->request->param();
            $machine->allowField(true)->save($params);
        }
        $this->success('修改成功');
    }
    /**
     * 删除机器
     * */
    public function machineDel(){
        if (!$this->request->param("id")) $this->error("机器序号不能为空");
        $machine=Machine::where(["id"=>$this->request->param("id")])->find();
        if(empty($machine)) $this->error("机器不存在");
        $machine->delete();
        $this->success('删除成功');
    }
}
